<!-- face-login -->
<template>
    <div class="face-login">
        <!-- 信息提示 -->
        <div class="info">{{ info }}</div>
        <!--图片展示-->
        <div class="video">
            <video ref="video" width="462" height="462" autoplay></video>
        </div>

        <div class="face-reco"></div>
        <!--canvas截取流-->
        <canvas class="canv" ref="canvas" width="400" height="300"></canvas>
    </div>
</template>

<script>
import _ from 'lodash'
import {
    doLoginByFace,
    getUserInfo
} from '@/apis'
export default {
    name: "face-login",
    data() {
        return {
            info: "请开启相机权限",
            timer: null,
            headImgSrc: '@/assets/edit.png'
        };
    },
    methods: {
        // 调用摄像头
        callCamera() {
            // H5调用电脑摄像头API
            console.log('H5调用电脑摄像头API');
            let videoObj = { video: true };
            var errBack = function (error) {
                console.log("Video capture error: ", error.code);
            };
            if (navigator.mediaDevices.getUserMedia) { // Standard
                navigator.mediaDevices.getUserMedia(videoObj).then(stream => {
                    this.$refs["video"].srcObject = stream;
                    this.$refs["video"].play();
                    this.info = '请调整姿势，对准摄像头！'
                    console.log('摄像头开启');
                    this.startCap();
                });
            } else if (navigator.getUserMedia) { // WebKit-prefixed
                navigator.webkitGetUserMedia(videoObj, function (stream) {
                    this.$refs["video"].src = window.URL.createObjectURL(stream);
                    this.$refs["video"].play();
                }, errBack);
            } else if (navigator.webkitGetUserMedia) { // WebKit-prefixed
                navigator.webkitGetUserMedia(videoObj, function (stream) {
                    this.$refs["video"].src = window.URL.createObjectURL(stream);
                    this.$refs["video"].play();
                }, errBack);
            }
            else if (navigator.mozGetUserMedia) { // Firefox-prefixed
                navigator.mozGetUserMedia(videoObj, function (stream) {
                    this.$refs["video"].mozSrcObject = stream;
                    this.$refs["video"].play();
                }, errBack);
            } 
        },
        // 关闭摄像头
        closeCamera() {
            if (!this.$refs["video"].srcObject) {
                this.dialogCamera = false;
                return;
            }
            let stream = this.$refs["video"].srcObject;
            let tracks = stream.getTracks();
            tracks.forEach((track) => {
                track.stop();
            });
            this.$refs["video"].srcObject = null;
            this.clearInterval();
        },

        // 调用接口传图片请求
        async handleLogInByFace (file) {
            try {
                //let id = 99;
                let id = window.localStorage.getItem('organizationId');
                var formdata=new FormData();
                formdata.append("file", file);
                formdata.append("deptId", id);
                let res = await doLoginByFace(formdata);
                console.log('facelogin', res);
                let {
                    code,
                    msg,
                    data
                } = res.data;
                if (code == 200) {
                    this.info = msg;
                    this.closeCamera();
                    sessionStorage.setItem('token', data);
                    this.getUser(); 
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    
                      
                } else {
                    this.info = msg;
                    this.startCap();
                }
            } catch(e) {
                console.log('requestOutStore',e)
            }
        },

        // 获取用户信息
        async getUser () {
            try {
                let res = await getUserInfo();
                console.log('获取用户信息', res);
                let {
                    code,
                    msg,
                    data
                } = res.data;
                if (code == 200) {
                    let {
                        username
                    } = data;
                   this.$store.commit('SET_USER', username.trim());
                   if (this.$route.query.redirect) { //如果存在参数
                        let redirect = this.$route.query.redirect
                        this.$router.push(redirect).catch({});//则跳转至进入登录页前的路由
                    } else {
                        this.$router.push('/home').catch({});
                    }
                } else if (code == -2) {
                    this.$message({
                        type: 'error',
                        message: `${msg}`
                    })
                    this.$store.commit('CLEAR_LOGIN');
                    this.$router.push('/login').catch({});  
                } else {
                    this.info = msg;
                    this.startCap();
                }
            } catch(e) {
                console.log('requestOutStore',e)
            }
        },

        // 截取图片
        startCap: _.debounce(function () {
            if (!this.$refs["canvas"]) return;
            let ctx = this.$refs["canvas"].getContext("2d");
            // 把当前视频帧内容渲染到canvas上
            ctx.drawImage(this.$refs["video"], 0, 0, 400, 300);
            // 转base64格式、图片格式转换、图片质量压缩
            let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7);
            // console.log('img --- ', imgBase64);
            // let str = imgBase64.replace("data:image/jpeg;base64,", "");
            var blob = this.dataURLtoBlob(imgBase64);
            var file = this.blobToFile(blob, Date.now());
            this.handleLogInByFace(file)
            
        }, 800),

        //将base64转换为blob
        dataURLtoBlob (dataurl) { 
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        },
        //将blob转换为file
        blobToFile (theBlob, fileName){
            theBlob.lastModifiedDate = new Date();
            theBlob.name = fileName;
            return theBlob;
        },

        // 清除定时器
        clearInterval () {
            if (this.timer) {
                clearInterval();
                this.timer = null;
            }  
        }
    },
    created() {
        this.callCamera();
    },
    beforeDestroy() {
        this.closeCamera();
        this.clearInterval();
    },
};
</script>
<style lang='scss' scoped>
.face-login {
    width: 100%;
    height: 100%;
    overflow: auto;
    position: relative;

    .info {
        position: absolute;
        top: 5%;
        left: 50%;
        transform: translateX(-50%);
        font-size: 22px;
        color: #fff;
    }

    .video {
        width: 462px;
        height: 462px;
        top: 50%;
        left: 50%;
        position: absolute;
        border-radius: 50%;
        margin-left: -218px;
        margin-top: -228px;
        overflow: hidden;

        video {
            object-fit: fill;
        }
    }

    .face-reco {
        width: 600px;
        height: 600px;
        top: 50%;
        left: 50%;
        margin-left: -300px;
        margin-top: -300px;
        background: url("../../assets/face-id.svg") no-repeat center center;
        background-size: 100% 100%;
        position: absolute;
    }

    .canv {
        display: block;
        position: absolute;
        z-index: -999;
    }
}
</style>